﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VersionSwitcher.Constants;
using VersionSwitcher.Workers;
using VersionSwitcher.Exceptions;
using VersionSwitcher.Loggers;

namespace VersionSwitcher
{
    class Program
    {
        private static FileWorker fileWorker;
        private static PackageLoaderWorker plWorker;
        private static BatWorker batWorker;
        private static EclipseSettingsWorker esWorker;
        private static ILogger logger;

        static void Main(string[] args)
        {
            InitLogger();
            try
            {
                ValidateArguments(args);
                bool isAutoMode = !(args[0].ToLower().Trim() == KeyWords.Manual.ToLower().Trim());
                InitWorkers(isAutoMode, args);
                fileWorker.CreateMainFolder();
                plWorker.Initialize();
                plWorker.Start();
                /*batWorker.Initialize();
                batWorker.Start();
                esWorker.CreateSettings();*/
                

            }
            catch (BusinessException e)
            {
                LogError(e);
                return;
            }
        }

        private static void InitLogger()
        {
            logger = new ConsoleLogger();
        }

        private static void LogError(BusinessException e)
        {
            logger.Log(e.Message);
            if (e.InnerException != null)
            {
                logger.Log(e.InnerException.StackTrace);
            }
        }

        private static void InitWorkers(bool isAutoMode, string[] args)
        {
            string fileParamter = isAutoMode ? args[0] : args[1];
            string svnParameter = isAutoMode ? args[0] : args[2];
            fileWorker = new FileWorker(fileParamter, isAutoMode, logger);
            SvnWorker svnWorker = new SvnWorker(svnParameter, isAutoMode, logger);
            plWorker = new PackageLoaderWorker(fileWorker, svnWorker, logger);
            batWorker = new BatWorker(fileWorker, svnWorker, logger);
            esWorker = new EclipseSettingsWorker(fileWorker, svnWorker, logger);
        }

        private static void ValidateArguments(string[] args)
        {
            if (args.Length == 0)
            {
                throw new BusinessException(ErrorMessages.Error + ErrorMessages.StartWithoutAtguments);
            }
            if (args.Length < 3 && args[0].Trim().ToLower() == KeyWords.Manual.Trim().ToLower())
            {
                throw new BusinessException(ErrorMessages.Error + ErrorMessages.NotEnoughArgumentsForManualMode);
            }
        }
    }
}
